package two.chapter_1.c1_3;

import edu.princeton.cs.algs4.StdRandom;

import java.util.Iterator;

public class RandomQueue<Item> implements Queue<Item> {
    private int size;
    private Item[] items;
    private static final int DEFAULT_CAPACITY = 10;

    public RandomQueue() {
        items = (Item[]) new Object[DEFAULT_CAPACITY];
    }

    @Override
    public void enqueue(Item item) {
        ensureCapacity(size + 1);
        items[size++] = item;
    }

    private void ensureCapacity(int length) {
        if (length >= items.length) {

            int newLength = items.length * 2;
            resize(newLength);

        }
    }

    private void resize(int newLength) {
        Item[] newItems = (Item[]) new Object[newLength];
        System.arraycopy(items, 0, newItems, 0, Math.min(newLength, items.length));
        items = newItems;
    }

    @Override
    public Item dequeue() {
        if (isEmpty()) {
            throw new CollectionEmptyException();
        }
        if (size > 1) {
            int pos = StdRandom.uniform(size - 1);
            swap(pos, size - 1);
        }
        Item last = items[size - 1];
        items[size - 1] = null;

        size--;

        if (size > 0 && size * 4 <= items.length) {
            resize(items.length / 2);
        }
        return last;
    }

    /**
     * 随机返回一个元素但不删除他
     *
     * @return
     */
    public Item sample() {
        int pos = StdRandom.uniform(size);
        return items[pos];
    }

    private void swap(int srcPos, int destPos) {
        Item temp = items[srcPos];
        items[srcPos] = items[destPos];
        items[destPos] = temp;
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new RandomIter();
    }

    private class RandomIter implements Iterator<Item> {
        private int pos;
        private Item [] shuffleItems;
        public RandomIter() {
            shuffleItems= (Item[]) new Object[size];
            System.arraycopy(items,0,shuffleItems,0,size);
            StdRandom.shuffle(shuffleItems);
        }

        @Override
        public boolean hasNext() {
            return pos<size;
        }

        @Override
        public Item next() {
            return shuffleItems[pos++];
        }

        @Override
        public void remove() {

        }
    }
}
